package cn.ilikes.tools.hbase.jpa.clazzes;

import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;

import cn.ilikes.tools.hbase.jpa.JPAHBaseRuntimeException;
import cn.ilikes.tools.hbase.jpa.JPAHbasePersistenUnitEnv;
import cn.ilikes.tools.hbase.jpa.clazzes.resources.ResourcesloadListener;
import cn.ilikes.tools.logs.Loggerfactory;

public class JPAHbaseSysClassLoader extends ABJPAHbaseClassLoader implements IJPAHbaseFilterClassLoader, ResourcesloadListener {

	private static Logger logger = Loggerfactory.instance(JPAHbaseSysClassLoader.class);

	private List<ClassFilter> classFilteres = new ArrayList<ClassFilter>();

	private JPAHbasePersistenUnitEnv hbasePersistenUnitEnv;

	public JPAHbaseSysClassLoader(ClassLoader parentClassLoader) {
		super(parentClassLoader);

	}

	public JPAHbaseSysClassLoader(JPAHbasePersistenUnitEnv hbasePersistenUnitEnv) {
		super(Thread.currentThread().getContextClassLoader());
		this.hbasePersistenUnitEnv = hbasePersistenUnitEnv;

	}

	protected void init() {
		addResourcesloadListener(this);
	}

	private void classFiltere(String resourceClassName) {
		String className = resourceClassName.substring(0, resourceClassName.lastIndexOf(".class"));

		for (ClassFilter classFilter : classFilteres) {
			if (classFilter.isContain(className)) {
				try {
					Class clazz = loadClass(className);
					classFilter.filter(className, clazz);
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void loadResources(String resourceName, ResourcesType resourcesType) {
		if (!resourcesType.name().equals(ResourcesType.classes.name()))
			return;
		classFiltere(resourceName);
	}

	@Override
	public void addJPAHbaseFilterClassLoader(ClassFilter filter) {
		classFilteres.add(filter);

	}

	@Override
	public void hbaseEntityFilter() {
		{

			Loggerfactory.info(logger, "start init  hbasePersistenUnitEnv  pu name  " + hbasePersistenUnitEnv.gethBasePersistenceUnitMetadata().getPersistenceUnitName()
					+ " JPAHbaseClassLoader ! ");
			String classPaths_ = (String) System.getProperties().get("java.class.path");
			String[] classPaths = classPaths_.split(":");
			for (String classPath : classPaths) {
				try {
					Loggerfactory.info(logger, "start load   JPA Hbase System   lib : " + classPath);
					loadResources(new File(classPath).toURI().toURL());
				} catch (MalformedURLException e) {
					Loggerfactory.error(logger, e);
					throw new JPAHBaseRuntimeException(e);
				}
			}
			hbasePersistenUnitEnv.setHbaseSysClassLoader(this);
		}

	}

}
